#include<pthread.h>
#include<iostream>
#include<string>
#include<unistd.h>

const int nums = 5;
//添加全局条件变量
pthread_cond_t  gcond = PTHREAD_COND_INITIALIZER;
//添加全局锁
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;

void *Wait(void *args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&gmutex); 

        pthread_cond_wait(&gcond, &gmutex);//这里就是线程等待的位置
        usleep(10000);
        
        std::cout << "I am ：" << name << std::endl;
        
        pthread_mutex_unlock(&gmutex); 
        
        usleep(100000);
    }
}


int main()
{
    pthread_t threads[nums];
    for(int i = 0; i < nums; i++)
    {
        char *name = new char[1024];
        snprintf(name, 1024, "thread-%d", i+1);
        pthread_create(threads + i, nullptr, Wait, (void *)name);
    }

    //主线程唤醒其他线程
    while(true)
    {
        pthread_cond_signal(&gcond);
        std::cout << "唤醒一个线程"<< std::endl;
        sleep(2);
    }




    for(int i = 0; i < nums; i++)
    {
        pthread_join(threads[i], nullptr);
    }

    return 0;
}
